package io.mft.as.ar.gateway.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.hutool.core.util.ObjectUtil;
import io.mft.as.ar.gateway.config.bean.ARServiceConfig;
import io.mft.as.ar.gateway.exception.GatewayClientException;
import io.mft.commons.config.ConfigProvider;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class BusIdConfig
{
    
    private static boolean                    IS_USE_AR_ROUTE   = true;                               //是否使用AR路由，从配置文件Configuration.xml中配置
                                                                                                        
    private static Map<String, BusConfigBean> SERVICE_CONFIG    = new ConcurrentHashMap<String, BusConfigBean>();
    static ConcurrentHashMap<String, String> serverKey=new ConcurrentHashMap<String, String>();
    // 默认的BUS服务器信息
    private static String                     DEFAULT_SYSTEM_ID = "";
    private final static String CONFIG_FILE_NAME = "BusIdConfig.xml";
    private static BusIdConfig  instance=new BusIdConfig();
    public static BusIdConfig getInstance() {
		return instance;
	}
    static
    {
    	try {
            String isUseArRoute = ConfigProvider.get("system.isUseArRoute","1");//是否使用AR路由，默认不使用，为1时使用
            if ( "1".equals(isUseArRoute))
            {
                IS_USE_AR_ROUTE = true;
            }
            else
            {
                IS_USE_AR_ROUTE = false;
            }
		} catch (Throwable e) {
			log.error("",e);
		}

    }
    
    private BusIdConfig()
    {
    }
    
    static
    {
    	loadConfigV2();
    }
    private synchronized static void loadConfigV2()
    {
    	/**
        try
        {
            Document document = XMLHelper.getDocument(BusIdConfig.class, CONFIG_FILE_NAME);
            if ( document == null )
            {
                log.error("未找到配置文件[" + CONFIG_FILE_NAME + "]");
                return;
            }
            Element rootElement = document.getRootElement();
            
            String defaultSystemId = rootElement.attributeValue("default", "");// 默认执行的服务器信息
            String firstSystemId = "";// BusIdConfig.xml中配置的第一个节点信息
            
            int i = 0;
            
            Map<String, HashMap<String, String>> systemConfieMap = null;
            List<Element> serviceList = rootElement.elements("Service");
            if ( serviceList != null && !serviceList.isEmpty() )
            {
                systemConfieMap = new HashMap<String, HashMap<String, String>>();
                for (Element serviceElement : serviceList)
                {
                    String systemId = serviceElement.attributeValue("SystemID");
                    if ( ObjectUtil.isEmpty(systemId) )
                    {
                        continue;
                    }
                    
                    int systemNo = Integer.valueOf(serviceElement.attributeValue("SystemNo"));
                    
                    String busConfigId = serviceElement.attributeValue("BusConfigId");
                    
                    if ( i == 0 )
                    {
                        firstSystemId = systemId;
                        i++;
                    }
                    
                    BusConfigBean busConfigBean = new BusConfigBean();
                    busConfigBean.setSystemId(systemId);
                    busConfigBean.setSystemNo(systemNo);
                    busConfigBean.setBusConfigId(busConfigId);
                    
                    SERVICE_CONFIG.put(systemId, busConfigBean);
                }
            }
            
             //如果配置了default，需要比较default的值是否与server的id一致，如果不一致，取第一个server的id作为默认值
            if ( StringHelper.isEmpty(defaultSystemId) || !SERVICE_CONFIG.containsKey(defaultSystemId) )
            {
                defaultSystemId = firstSystemId;
            }
            DEFAULT_SYSTEM_ID = defaultSystemId;
            
        }
        catch (Exception ex)
        {
            log.error("", ex);
        }
        **/
    }
   
    
    /**
    *
    * 描述： 作者：李炜 时间：Nov 26, 2013 11:35:03 AM
    *
    * @param id
    * @return
    */
    public static BusConfigBean getBusConfigBean(String systemId)
    {
        if ( SERVICE_CONFIG.containsKey(systemId) )
        {
            return SERVICE_CONFIG.get(systemId);
        }
        else
        {
            throw new GatewayClientException( -1, "服务器信息[" + systemId + "]配置不存在");
        }
    }
    
    /**
     * 
     * @描述: 获取根据systemId获取系统编号 
     * @作者: liwei
     * @创建日期: 2017年11月25日 下午3:04:03
     * @param systemId
     * @return
     */
    public static int getSystemNo(String systemId)
    {
        int systemNo = 0;
        if ( ObjectUtil.isEmpty(systemId) )
        {
            if ( BusIdConfig.isUseArRoute() )
            {
                systemId = BusIdConfig.getDefaultSystemId();
            }
            else
            {
                systemId = BusConfig.getDefaultServerId();
            }
        }
        
        if ( BusIdConfig.isUseArRoute() )
        {
            BusConfigBean busConfigBean = BusIdConfig.getBusConfigBean(systemId);
            if ( busConfigBean != null )
            {
                systemNo = busConfigBean.getSystemNo();
            }
        }
        else
        {
            systemNo = 0;
        }
        return systemNo;
    }
    
    /**
     * 
     * @描述: 根据systemId获取BusConfig.xml中的id 
     * @作者: liwei
     * @创建日期: 2017年11月26日 下午4:59:27
     * @param systemId
     * @return
     */
    public static String getBusConfigId(String systemId)
    {
        String busConfigId = "";
        if ( ObjectUtil.isEmpty(systemId) )
        {
            if ( BusIdConfig.isUseArRoute() )
            {
                systemId = BusIdConfig.getDefaultSystemId();
            }
            else
            {
                systemId = BusConfig.getDefaultServerId();
            }
        }
        
        if ( BusIdConfig.isUseArRoute() )
        {
            BusConfigBean busConfigBean = BusIdConfig.getBusConfigBean(systemId);
            if ( busConfigBean != null )
            {
                busConfigId = busConfigBean.getBusConfigId();
            }
        }
        else
        {
            busConfigId = systemId;
        }
        
        return busConfigId;
    }
    
    /**
     * 
     * @描述: 获取默认的系统编号
     * @作者: liwei
     * @创建日期: 2017年11月24日 下午9:27:52
     * @return
     */
    public static String getDefaultSystemId()
    {
        if ( BusIdConfig.isUseArRoute() )
        {
            return DEFAULT_SYSTEM_ID;
        }
        else
        {
            return BusConfig.getDefaultServerId();
        }
    }
    
    /**
     * 
     * @描述: 是否使用AR路由 
     * @作者: liwei
     * @创建日期: 2017年11月25日 上午11:48:50
     * @return
     */
    public static boolean isUseArRoute()
    {
        return IS_USE_AR_ROUTE;
    }
    
	public static boolean addConfig(ARServiceConfig config) {
		boolean s=false;
		String key=config.getBusconfigid()+config.getSystemid()+config.getSystemno();
		if (!serverKey.containsKey(key)&&SERVICE_CONFIG.containsKey(config.getSystemid())) {
			buildConfig(config);
			serverKey.put(key,key);
			s=true;
		}
		if (!SERVICE_CONFIG.containsKey(config.getSystemid())) {
			buildConfig(config);
			serverKey.put(key,key);
			s=true;
		}
		return s;
	}
	
	private static void buildConfig(ARServiceConfig config) {
        String systemId = config.getSystemid();
        if ( ObjectUtil.isEmpty(systemId) )
        {
           return;
        }
        int systemNo = Integer.valueOf(config.getSystemno());
        String busConfigId = config.getBusconfigid();
        BusConfigBean busConfigBean = new BusConfigBean();
        busConfigBean.setSystemId(systemId);
        busConfigBean.setSystemNo(systemNo);
        busConfigBean.setBusConfigId(busConfigId);
        SERVICE_CONFIG.put(systemId, busConfigBean);
	}
}
